<template>
  <div class="purchase-incoming-list" style="height: calc(100vh - 104px); padding: 20px;">


    <div style=" background: #fff; border-radius: 10px; margin-bottom: 10px; padding: 20px 25px 10px;">
      <div class="dashboard-inner">
        进货单报表
        <el-tooltip class="item" effect="dark" content="温馨提示：表格对应列可以通过拖动改变表格宽度" placement="top">
          <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
        </el-tooltip>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="按单据" name="first">
          <div style="display: flex;">
            <common-operation-form style="margin-top: 6px; flex: 1;" :list="list"/>
            <common-operation-form style="margin-top: 6px;" :marginRight="'0px'" :marginLeft="'6px'" :list="rightList"/>
          </div>
        </el-tab-pane>
        <el-tab-pane label="按明细" name="second">
          <common-operation-form style="margin-top: 6px;"  :list="list2"/>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div style="  height: calc(100% - 90px); background: #fff;" class="settement-right-content " >
      <div v-show="activeName === 'first'" style="width: calc(100% - 50px); margin-left: 25px; margin-right: 25px;">
        <el-table style="margin-top: 15px;" :row-class-name="tableRowClassName" :height="windowHeight - 60" show-summary  :summary-method="getSummaries"
                  @selection-change="handleSelectionChange"
                  v-loading="table.loading" :data="table.data" border ref="purchaseIncomingTableRef">
          <el-table-column
              type="selection" fixed="left" align="center"
              :header-align="`center`"
              width="55">
          </el-table-column>
          <el-table-column
              v-for="(item, index) in table.header1"
              :prop="item.prop"
              :index="index" align="center" :show-overflow-tooltip="true"
              :width="item.width || 'auto'" :header-align="`center`"
              :label="item.label">
            <template slot="header" slot-scope="scope">
              <span v-if="item.prop === 'info'" style=" ">
                {{item.label}}<span style="margin-left: 2px; opacity: 0.9; font-size: 10px;">(数量/进货价)</span>
              </span>
              <span v-else>{{ item.label }}</span>
            </template>
            <template slot-scope="scope">
              <span v-if="item.prop === 'createDate'" style=" ">
                {{ parseTime(new Date(scope.row[item.prop]), '{y}-{m}-{d}') }}
              </span>
              <span v-else-if="item.prop === 'invoice'" style=" ">
                <span v-if="scope.row.invoice === false">无需开票</span>
                <span v-else-if="scope.row.invoice && scope.row.invoiceCode === -1" style="color: red; font-weight: 500;">未开票</span>
                <span v-else-if="scope.row.invoice && scope.row.invoiceCode === 1" style="color: greenyellow; font-weight: 500;">已开票</span>
              </span>
              <span :style="`${scope.row[item.prop] > 0 ? 'color: red; ' : 'color: #000;'}`" v-else-if="item.prop === 'unpaidAmount'">
                 {{scope.row[item.prop]}}
              </span>
              <span v-else style=" ">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column
              v-for="(item, index) in table.header2"
              :prop="item.prop"
              :index="index" :align="`center`"
              :width="item.width || 'auto'" :header-align="`center`" fixed="right"
              :label="item.label">
            <template slot-scope="scope">
              <span v-if="item.prop === 'defaultEmployee'" style=" ">
                {{ scope.row[item.prop] ? '是' : '否' }}
              </span>
              <span v-else-if="item.prop === 'paymentStatus'" style=" ">
                <span v-if="paymentStatus(scope.row)">已付款</span>
                <span v-else style="color: red; font-weight: 500;">部分付款</span>
              </span>
              <span v-else-if="item.prop === 'audit'" style=" ">
                <span v-if="scope.row[item.prop]">已审核</span>
                <span v-else style="color: red; font-weight: 700;">待审核</span>
              </span>
              <span v-else style=" ">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <div style="display: flex;">
                <el-tooltip content="打印" slot="reference" placement="top">
                  <el-button size="mini" icon="el-icon-printer" type="success" circle @click="print(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="编辑" slot="reference" placement="top">
                  <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="edit(scope.row, scope.$index)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" slot="reference" placement="top">
                  <el-button size="mini" @click="del(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>


        <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                       :current-page="page.pageNumber" @size-change="sizeChange" @current-change="currentChange"
                       layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                       :total="page.total">
        </el-pagination>
      </div>
      <div v-show="activeName === 'second'"  style="width: calc(100% - 50px); margin-left: 25px; margin-right: 25px;">
        <el-table style="margin-top: 15px;"
                  :row-class-name="tableRowClassName" :height="windowHeight - 60" show-summary  :summary-method="getSummaries2"
                  v-loading="table.loading" :data="table.data2" border ref="purchaseIncomingTableRef2">
          <el-table-column
              v-for="(item, index) in table.header3"
              :prop="item.prop"
              :index="index" align="center" :show-overflow-tooltip="true"
              :width="item.width || 'auto'" :header-align="`center`"
              :label="item.label">
            <template slot-scope="scope">
              <span v-if="item.prop === 'createDate'" style=" ">
                {{ parseTime(new Date(scope.row[item.prop]), ) }}
              </span>
              <span v-else-if="item.prop === 'invoice'" style=" ">
                <span v-if="scope.row.invoice === false">无需开票</span>
                <span v-else-if="scope.row.invoice && scope.row.invoiceCode === -1" style="color: red; font-weight: 500;">未开票</span>
                <span v-else-if="scope.row.invoice && scope.row.invoiceCode === 1" style="color: greenyellow; font-weight: 500;">已开票</span>
              </span>
              <span style=" font-weight: 500; " v-else-if="item.prop === 'price' || item.prop === 'totalAmount'
                    || item.prop === 'inventory'">
                 {{scope.row[item.prop]}}
              </span>
              <span v-else style=" ">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                       :current-page="page.pageNumber" @size-change="sizeChange2" @current-change="currentChange2"
                       layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               width="95%" v-dialog-drag
               title="编辑进货单" :modal="false"
               custom-class="dialoginter7"
               :visible.sync="dialog.dialogVisible">
      <span slot="title">
        编辑进货单
        <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
          <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
        </el-tooltip>
        <el-tag size="small" style="margin-left: 20px;" v-if="dialog.formData && dialog.formData.audit" type="success" effect="dark">已审核</el-tag>
        <el-tag size="small" style="margin-left: 20px;" v-else type="danger" effect="dark">未审核</el-tag>
      </span>
      <edit v-if="dialog.formData && dialog.dialogVisible" @setPurchaseIncomingData="setPurchaseIncomingData" :formData="dialog.formData" style="padding: 0 !important;"/>
    </el-dialog>


    <print-dialog  :print-dialog-visible="printDialog.printDialogVisible" :templateData="printDialog.templateData" @setPrintData="setPrintData"/>

    <print-select-dialog  :print-dialog-visible="printDialog.templateDialogVisible"
                          :type-name="printDialog.chooseItem && printDialog.chooseItem.typeName"
                          @setPrintData="setPrintData"/>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import edit from "@/components/PurchaseIncoming/edit.vue";
import Print from "@/components/PurchaseIncoming/print.vue";
import {getPurchaseIncoming, deletePurchaseIncomingByID, audit, getPurchaseIncomingByID} from "@/api/purchaseIncoming";
import {getUserInfo} from "@/utils/auth";
import {calculateTwoValue, deepClone, documentTypeOptions, formatAmount, keepTwoDecimalFull, parseTime} from "@/utils";
import printSelectDialog from "@/views/print-template/printSelectDialog.vue";
import printDialog from "@/views/print-template/printDialog.vue";

export default {
  // name: 'purchase_incoming_report',
  components: {CommonOperationForm, printSelectDialog, printDialog, CommonDialogForm, edit, Print},
  data() {
    return {
      activeName: 'first',
      table: {
        data: [],
        data2: [],
        header1: [
          {
            prop: "createDate",
            width: '110px',
            label: "业务日期"
          },
          {
            prop: "documentNumber",
            label: "单据编号",
            width: "150px",
          },
          {
            prop: "supplierName",
            label: "供应商",
          },
          {
            prop: 'info',
            width: "150px",
            label: '进货商品',
          },
          {
            prop: 'payableAmount',
            label: '单据金额',
          },
          {
            prop: 'payAmount',
            label: '已付金额',
          },
          {
            prop: 'unpaidAmount',
            label: '未付金额',
          },
          {
            prop: 'accountName',
            label: '制单人',
          },
          {
            prop: 'settlementAccount',
            label: '结算账户',
          },
          {
            prop: 'invoice',
            label: '发票状态',
          },
          {
            prop: 'remarks',
            label: '备注信息'
          },
        ],
        multipleSelection: [],
        header2: [
          {
            prop: 'paymentStatus',
            label: '付款状态',
            fixed: 'right',
          },
          {
            prop: 'audit',
            label: '审核状态',
            fixed: 'right',
          }
        ],
        header3: [
          {
            prop: 'createDate',
            width: '150px',
            label: '单据日期',
          },
          {
            prop: 'documentNumber',
            label: '单据编号',
            width: '125px',
          },
          {
            prop: 'supplierName',
            label: '供应商',
          },
          {
            prop: 'productName',
            label: '商品名称',
          },
          {
            prop: '',
            label: '辅助属性',
          },
          {
            prop: 'specification',
            label: '规格型号',
          },
          {
            prop: 'unit',
            label: '商品单位',
          },
          {
            prop: 'inventory',
            label: '数量',
          },
          {
            prop: 'purchaseUnitPrice',
            label: '单价',
          },
          {
            prop: 'purchaseTotalAmount',
            label: '金额',
          },
          {
            prop: 'accountName',
            label: '制单人',
          },
          {
            prop: 'productRemarks',
            label: '商品备注',
          },
          {
            prop: 'purchaseIncomingRemarks',
            label: '单据备注',
          }
        ],
      },
      dialog: {
        dialogVisible: false,
        formData: null,
        rowIndex: -1,
      },
      printDialog: {
        chooseItem: null,
        templateData: {
          templateTypeName: '',
          templateID: '',
          template: {},
        },
        printDialogVisible: false,
        templateDialogVisible: false,
      },
      rightList: [
        {
          type: 'button',
          buttonText: '审核',
          // buttonType: "success",
          event: () => {
            if (this.table.multipleSelection.length <= 0) {
              this.$message.error("请先勾选择需要审核的单据");
              return;
            }
            let IDList = [];
            for (let i = 0; i < this.table.multipleSelection.length; i++) {
              let {_id} = this.table.multipleSelection[i];
              IDList.push(_id);
            }

            audit({
              auditStatus: true,
              IDList,
            }).then(res => {
              console.log(res);
              this.$message.success("操作成功");
              // this.page.pageNumber = 1;
              this.getPurchaseIncomingList();
            });
          }
        },
        {
          type: 'button',
          buttonText: '反审核',
          // buttonType: "success",
          event: () => {
            if (this.table.multipleSelection.length <= 0) {
              this.$message.error("请先勾选择需要审核的单据");
              return;
            }
            let IDList = [];
            for (let i = 0; i < this.table.multipleSelection.length; i++) {
              let {_id} = this.table.multipleSelection[i];
              IDList.push(_id);
            }

            audit({
              auditStatus: false,
              IDList,
            }).then(res => {
              console.log(res);
              this.$message.success("操作成功");
              // this.page.pageNumber = 1;
              this.getPurchaseIncomingList();
            });
          }
        },
        {
          type: 'button',
          buttonText: '删除',
          buttonType: "danger",
          event: () => {
            if (this.table.multipleSelection.length <= 0) {
              this.$message.error("请先勾选择需要删除的单据");
              return;
            }

            console.log(this.table.multipleSelection);
            let IDList = [];
            for (let i = 0; i < this.table.multipleSelection.length; i++) {
              let {_id} = this.table.multipleSelection[i];
              IDList.push(_id);
            }
            deletePurchaseIncomingByID({IDList}).then(res => {
              console.log(res);
              this.page.pageNumber = 1;
              this.getPurchaseIncomingList();
            });
          }
        },
      ],
      list: [
        {
          type: 'input',
          text: '商品名称：',
          width: '70px',
          inputWidth: '120px',
          value: '',
        },
        {
          type: 'input',
          text: '单据编号：',
          inputWidth: '120px',
          width: '70px',
          value: '',
        },
        {
          type: 'supplierSetting',
          text: '供应商名称：',
          width: '95px',
          selectWidth: '200px',
          multiple: false,
          value: null,
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.page.pageNumber = 1;
            this.getPurchaseIncomingList();
          }
        },
      ],
      list2: [
        {
          type: 'input',
          text: '商品名称：',
          width: '70px',
          inputWidth: '120px',
          value: '',
        },
        {
          type: 'input',
          text: '单据编号：',
          width: '70px',
          inputWidth: '120px',
          value: '',
        },
        {
          type: 'warehouse',
          text: '所属仓库：',
          width: '80px',
          selectWidth: '140px',
          multiple: false,
          value: null,
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.page.pageNumber = 1;
            this.getPurchaseIncomingListByDetail();
          }
        },
      ],
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      },
    }
  },
  activated() {
    console.log("activated");
    this.getPurchaseIncomingList();
  },
  mounted() {
    console.log("mounted");
    this.getPurchaseIncomingList();
  },
  methods: {
    parseTime,
    setPrintData(v) {
      this.printDialog.templateData = v?.templateData;
      this.printDialog.printDialogVisible = v?.printDialogVisible;
      this.printDialog.templateDialogVisible = v?.templateDialogVisible;
    },
    printDialogStatus(v) {
      this.printDialog.printDialogVisible = v;
    },
    paymentStatus(row) {
      let {unpaidAmount} = row;
      return unpaidAmount <= 0; // 结清 true 未结清 false
    },
    print(item) {
      this.printDialog.chooseItem = item;
      this.printDialog.templateDialogVisible = true;
    },
    edit(row, index) {
      console.log(row);
      this.dialog.dialogVisible = true;
      this.dialog.formData = deepClone(row);
      this.dialog.rowIndex = index;
      this.$refs.purchaseIncomingTableRef?.doLayout();
    },
    sizeChange(val) {
      console.log(this.page);
      this.page.pageSize = val;
      this.page.pageNumber = 1;
      this.getPurchaseIncomingList();
    },
    currentChange(val) {
      this.page.pageNumber = val;
      this.getPurchaseIncomingList();
    },
    sizeChange2(val) {
      console.log(this.page);
      this.page.pageSize = val;
      this.page.pageNumber = 1;
      this.getPurchaseIncomingListByDetail();
    },
    currentChange2(val) {
      this.page.pageNumber = val;
      this.getPurchaseIncomingListByDetail();
    },
    del(row) {
      console.log(row);
      let IDList = [row._id,];
      deletePurchaseIncomingByID({IDList}).then(res => {
        console.log(res);
        this.dialog.rowIndex = -1;
        this.page.pageNumber = 1;
        this.getPurchaseIncomingList();
      });
    },
    handleSelectionChange(val) {
      this.table.multipleSelection = val;
    },
    tableRowClassName({row, rowIndex}) {
      console.log(rowIndex, this.dialog.rowIndex);
      if (rowIndex === this.dialog.rowIndex) {
        return 'highlight';
      }
      return '';
    },
    handleClick() {
      this.page.pageNumber = 1;
      if (this.activeName === 'first') {
        this.getPurchaseIncomingList();
      } else {
        this.getPurchaseIncomingListByDetail();
      }
      this.dialog.rowIndex = -1;
    },
    setPurchaseIncomingData(data) {
      console.log(data);
      // 审核相关操作后不关闭弹出框
      // this.dialog.dialogVisible = false;
      this.dialog.formData = data;
      let { productInfo } = data;
      this.table.data[this.dialog.rowIndex] = data;
      this.table.data = [... this.table.data];
      let info = "";
      for (let j = 0; j < productInfo.length; j++) {
        const ppi = productInfo[j];
        info += ppi.productName;
        info += "(";
        info += ppi.inventory;
        info += "：";
        info += formatAmount(ppi.purchaseUnitPrice);
        info += ")";
        if (j !== productInfo.length - 1) {
          info += ",";
        }
      }

      data['info'] = info;
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        sums[index] = '';
      });

      let totalpayableAmount = 0.0;
      let totalpayAmount = 0.0;
      let totalunpaidAmount = 0.0;
      for (let i = 0; i < data.length; i++) {
        let {payableAmount, payAmount, unpaidAmount} = data[i];
        payableAmount = parseFloat(payableAmount);
        payAmount = parseFloat(payAmount);
        if (!isNaN(payableAmount)) {
          totalpayableAmount = calculateTwoValue(totalpayableAmount, payableAmount, 'add');
        }
        if (!isNaN(payAmount)) {
          totalpayAmount = calculateTwoValue(totalpayAmount, payAmount, 'add');
        }
        if (!isNaN(unpaidAmount)) {
          totalunpaidAmount = calculateTwoValue(totalunpaidAmount, unpaidAmount, 'add');
        }
      }

      sums[5] = totalpayableAmount + " ";
      sums[6] = totalpayAmount + " ";
      sums[7] = totalunpaidAmount + " ";
      this.$nextTick(() => {
        this.$refs.purchaseIncomingTableRef.doLayout();
      });
      return sums;
    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        sums[index] = '';
      });

      let totalPurchaseInventory = 0;
      let totalPurchasePrice = 0;
      let totalPurchaseTotalAmount = 0;
      for (let i = 0; i < data.length; i++) {
        let {purchaseUnitPrice, inventory, purchaseTotalAmount} = data[i];
        purchaseUnitPrice = parseFloat(purchaseUnitPrice) || 0;
        purchaseTotalAmount = parseFloat(purchaseTotalAmount) || 0;
        totalPurchasePrice = calculateTwoValue(totalPurchasePrice, purchaseUnitPrice, 'add');
        totalPurchaseInventory = calculateTwoValue(totalPurchaseInventory, inventory, 'add');
        totalPurchaseTotalAmount = calculateTwoValue(totalPurchaseTotalAmount, purchaseTotalAmount, 'add');
      }

      sums[7] = keepTwoDecimalFull(totalPurchaseInventory, 2);
      // sums[8] = keepTwoDecimalFull(totalPurchasePrice, 2);
      sums[9] = keepTwoDecimalFull(totalPurchaseTotalAmount, 2);
      this.$nextTick(() => {
        this.$refs.purchaseIncomingTableRef?.doLayout();
      });
      return sums;
    },
    getPurchaseIncomingList() {
      this.table.loading = true;
      getPurchaseIncoming({
        userID: getUserInfo().userID,
        pageSize: this.page.pageSize,
        productName: this.list[0].value,
        documentNumber: this.list[1].value,
        warehouseID: '',
        supplierID: this.list[2].value || '',
        pageNumber: this.page.pageNumber,
      }).then(res => {
        this.table.data = [];
        let {data} = res.data;
        this.page.total = res.data.page.totalDocuments;
        for (let i = 0; i < data.length; i++) {
          let {productInfo, createDate}  = data[i];
          this.table.data.push(data[i]);
          let info = "";
          for (let j = 0; j < productInfo.length; j++) {
            const ppi = productInfo[j];
            info += ppi.productName;
            info += "(";
            info += ppi.inventory;
            info += "：";
            info += formatAmount(ppi.purchaseUnitPrice);
            info += ")";
            if (j !== productInfo.length - 1) {
              info += ",";
            }
            console.log(info);
          }

          data[i]['info'] = info;
        }
        this.table.loading = false;
      });
    },
    getPurchaseIncomingListByDetail() {
      this.table.loading = true;
      getPurchaseIncoming({
        userID: getUserInfo().userID,
        pageSize: this.page.pageSize,
        productName: this.list2[0].value,
        documentNumber: this.list2[1].value,
        supplierID:   '',
        warehouseID: this.list2[2].value || '',
        pageNumber: this.page.pageNumber,
      }).then(res => {
        let {data} = res.data;
        this.table.data2 = [];
        this.page.total = res.data.page.totalDocuments;
        this.table.loading = false;

        for (let i = 0; i < data.length; i++) {
          let {productInfo, }  = data[i];

          for (let j = 0; j < productInfo.length; j++) {
            const ppi = productInfo[j];
            let d = Object.assign(JSON.parse(JSON.stringify(ppi)), data[i]);

            d['productRemarks'] = ppi['remarks'];
            d['purchaseIncomingRemarks'] = data[i]['remarks'];

            if(this.list2[2].value === '' || this.list2[2].value === null ) {
              this.table.data2.push(d);
            } else if (ppi['warehouse']._id === this.list2[2].value) {
              this.table.data2.push(d);
            }

          }
        }
        this.$nextTick(() => {
          this.table.loading = false;
          this.$refs.purchaseIncomingTableRef2?.doLayout();
        });
      });
    },
  }
}
</script>


<style lang="scss" scoped>
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}


.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}

.settement-right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: 100%;
  border-radius: 10px;
  padding-top: 10px;
  margin-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}

</style>

<style>
.purchase-incoming-list .el-table .el-table__footer-wrapper .cell{
  font-weight: 600;
  color: red;
}

.purchase-incoming-list .el-table .highlight {
  background: #f0f9eb;
}

.purchase-incoming-list .el-tabs__header {
  margin-bottom: 8px;
}
</style>


